//
//  UserAccount.m
//  weibo
//
//  Created by hp on 16/4/28.
//  Copyright © 2016年 hp. All rights reserved.
//

#import "UserAccount.h"
#import "NetworkTools.h"
#import "NSString+Path.h"
static UserAccount *instance = nil;
@implementation UserAccount
- (instancetype)initWithDictionary:(NSDictionary *)dic
{
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dic];
    }
    return self;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    
}

+ (instancetype)userAccountDictionary:(NSDictionary *)dic
{
    return  [[[self class] alloc] initWithDictionary:dic];
}

+ (instancetype)sharedUserAccount
{
    // 先保存一下
    if (instance==nil) {
        [self loadUserAccount];
    }
    
    if (instance==nil) { // 有可能是过期，也可能是没登录
        
        instance = [[UserAccount alloc] init];
    }

    return instance;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"access_token:%@ expires_in:%i uid:%@", self.access_token,self.expires_in,self.uid];
}


- (void)requestUserInfoSuccessBlock:(void(^)(UserAccount *account))successfulBlock
                        failedBlock:(void(^)(NSError *error))failedBlock
{
    NSString *path = @"2/users/show.json";
    NSDictionary *dict = @{@"access_token":self.access_token,@"uid":self.uid};
    // 3发送请求
    [[NetworkTools sharedNetworkTools] GET:path parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",dict);
        [self setValuesForKeysWithDictionary:dict];
        
    
        NSLog(@"%@,%@",self.screen_name,self.avatar_large);
        
        // 保存用户信息
        [self saveAccount];
        successfulBlock(self);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failedBlock(error);
    }];
}

- (BOOL)isLogined
{
    if (self.access_token.length>0) {
        return YES;
    }
    
    return NO;
}

#pragma mark - 归档功能

#define kUserAccount_Access_token @"access_token"
#define kUserAccount_Expires_in @"expires_in"
#define kUserAccount_Uid @"uid"

#define kUserAccount_Screen_name @"screen_name"
#define kUserAccount_Avatar_large @"avatar_large"
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.access_token forKey:kUserAccount_Access_token];
    [aCoder encodeInt:self.expires_in forKey:kUserAccount_Expires_in];
    [aCoder encodeObject:self.uid forKey:kUserAccount_Uid];
    [aCoder encodeObject:self.screen_name forKey:kUserAccount_Screen_name];
    [aCoder encodeObject:self.avatar_large forKey:kUserAccount_Avatar_large];
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        self.access_token = [aDecoder decodeObjectForKey:kUserAccount_Access_token];
        self.expires_in = [aDecoder decodeIntForKey:kUserAccount_Expires_in];
        self.uid = [aDecoder decodeObjectForKey:kUserAccount_Uid];
        self.screen_name = [aDecoder decodeObjectForKey:kUserAccount_Screen_name];
        self.avatar_large = [aDecoder decodeObjectForKey:kUserAccount_Avatar_large];
    }
    return self;
}

//+ (NSString *)filePath
//{
//    NSArray *myPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *myDocPath=myPath[0];
//    NSString *filePath = [myDocPath stringByAppendingPathComponent:@"account.plist"];
//    NSLog(@"%@",filePath);
//    return filePath;
//}
// 读取
+ (void)loadUserAccount
{
    UserAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:[@"account.plist" docPath]];
    
    if ([account.expire_date timeIntervalSinceNow]>0) {
        
        if (instance!=nil) {
            instance = account;
        }
    }
}
// 保存
- (void)saveAccount
{
    [NSKeyedArchiver archiveRootObject:self toFile:[@"account.plist" docPath]];
}
@end
